<?php

namespace app\admin\controller\user;
use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use fast\Random;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\Miner;
use app\common\controller\Backend;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $searchFields = 'id,mobile';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['invite'])
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['invite'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
                $v->invite_user =$this->model->where('id',$v->invite['invite_user_id'])->value('mobile');
                $id = Db::name('invite')->where('invite_user_id',$v->id)->column('user_id');
                $id[] = $v->id;
                $v->money = Db::name('user_miner')->where("miner_cat",1)->where('user_id','IN',$id)->sum('price');
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }


    public function miner($ids = null)
    {
        $row = $this->model->get($ids);
        $MinerModel = new Miner();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params['miner_id']) {
                Db::startTrans();
                try {
                    $number = isset($params['number'])?$params['number']:1;
                    $minerData = Miner::get($params['miner_id']);
                    $total_price = $number*$minerData['price'];
                    $total_output_value = $minerData['arithmetic_value']*$number*24;

                    //我的矿机
                    $now =time();
                    $createtime = strtotime(date("Y-m-d H",$now).":00:00");//取当前时间整点+1小时
                    for ($i=0; $i < $number; $i++) { 
                        $user_miner[$i]['user_id']      = $row['id'];
                        $user_miner[$i]['miner_id']     = $params['miner_id'];
                        $user_miner[$i]['miner_number'] = 1;
                        $user_miner[$i]['output_value'] = $minerData['output_value'];
                        $user_miner[$i]['arithmetic_value'] = $minerData['arithmetic_value'];
                        $user_miner[$i]['sum_earnings'] = $minerData['arithmetic_value']*$minerData['run_cycle'];
                        $user_miner[$i]['price']        = $minerData['price'];
                        $user_miner[$i]['miner_cat']    = $minerData['miner_cat'];
                        $user_miner[$i]['miner_type']   = $minerData['miner_type'];
                        $user_miner[$i]['run_cycle']    = $minerData['run_cycle'];
                        $user_miner[$i]['createtime']   = $createtime;
                        $user_miner[$i]['endtime']      = $createtime+$minerData['run_cycle']*3600;
                    }

                    $invite = Db::name('invite')->where('user_id',$row['id'])->find();
                    $all_parentid = explode(',', $invite['path']);
                    Db::name('user_miner')->insertAll($user_miner);

                    //是否成为直推用户
                    if(!$invite['status']){
                        Db::name('invite')->where('user_id',$row['id'])->update(['status'=>1]);
                        //累加上级直推人数
                        Db::name('user')
                        ->where(['id'=>$invite['invite_user_id']])
                        ->setInc('total_zt_person');
                    }

                    if($minerData['miner_cat'] ==1 || $minerData['miner_cat'] ==3){
                        //更新所有团队业绩
                        // $user = Db::name('user')
                        // ->where('id','in',$all_parentid)
                        // ->update([
                        // 'total_team_achievement' => Db::raw('total_team_achievement+'.$total_price)
                        // ]);

                        //是否满足升级(直推人数/团队业绩)
                        $invite_user = Db::name('user')
                        ->where(['id'=>$invite['invite_user_id']])
                        ->find();
                        $findLevel = $invite_user['level']+1;
                        $level = Db::name('user_level')
                        ->where(['id'=>$findLevel])
                        ->find();
                        if(($invite_user['total_zt_person']>=$level['zhitui_number'])&&($invite_user['total_team_achievement']>=$level['team_performance'])&&($invite_user['level']<7)){
                            Db::name('user')
                            ->where(['id'=>$invite_user_id])
                            ->setInc('level');
                        }
                    }
                    Db::commit();
                    $this->success();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                // if ($result !== false) {
                //     $this->success();
                // } else {
                //     $this->error(__('No rows were updated'));
                // }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $list = Miner::select();
        $this->view->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public function import()
    {
        // $this->error('已关闭');
        set_time_limit(0);
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $index = 0;
            $values = [];
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if(!is_null($val)){
                        $values[$index][] =$val;
                    }
                }
                $index++;
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$values) {
            $this->error(__('No rows were updated'));
        }
        // 启动事务
        Db::startTrans();
        try {
            $success = 0;
            $i=1;
            foreach ($values as $key => $value) {
                //$user = [];
                $find_user_id = Db::name('user')->where('mobile',$value[0])->value('id');
                if($find_user_id){
                    throw new Exception('第'.$i.'行导入失败,'.$value[0].'已注册');
                }
                $invite_user_id = Db::name('user')->where('mobile',$value[1])->value('id');
                if(!$invite_user_id){
                    throw new Exception('第'.$i.'行导入失败,'.$value[1].'推荐人未注册');
                }
                $user['username']       = $value[0];
                $user['nickname']       = '矿工'.$value[0];
                $user['salt']           = Random::alnum();
                $user['password']       = md5(md5($value[0]) . $user['salt']);
                $user['mobile']         = $value[0];
                $user['static_wallet']  = isset($value[2])?$value[2]:0;
                $user['level']          = 0;
                $user['group_id']       = 1;
                $user['createtime']     = time();
                $user['verify_status']  = 0;
                $user['status']         = 'normal';
                $user['invite_code']    = Random::alnum();
                $id = Db::name('user')->insertGetId($user);
                //体验矿机
                $now =time();
                $createtime = strtotime(date("Y-m-d H",$now).":00:00");//取当前时间整点+1小时
                $miner_cycle['user_id'] = $id;
                $miner_cycle['output_value'] = 0.05;
                $miner_cycle['arithmetic_value'] = 0.05/24;
                $miner_cycle['run_cycle'] = 2400;
                $miner_cycle['sum_earnings'] = 2400/100*0.05;
                $miner_cycle['createtime'] = $createtime;
                $miner_cycle['endtime'] = $createtime+2400*3600;
                Db::name("user_miner")->insert($miner_cycle);
                if($id){
                    $path = Db::name('invite')->where('user_id',$invite_user_id)->value('path');
                    $invite['user_id'] = $id;
                    $invite['invite_user_id'] = $invite_user_id;
                    $invite['path'] = $path.','.$id;
                    $invite['createtime'] = time();
                    $invite['status'] = 0;
                    Db::name('invite')->insertGetId($invite);
                }
                $i++;
                $success++;
            }
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            Db::rollback(); 
            $this->error($msg);
        } catch (\Exception $e) {
            Db::rollback(); 
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('成功导入'.$success.'条数据');
    }

        /**
     * 导入
     */
    public function importlevel()
    {
//        $this->error('已关闭');
//        set_time_limit(0);
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $index = 0;
            $values = [];
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        if(!is_null($val)){
                            $values[$index][] =$val;
                        }
                }
                $index++;
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$values) {
            $this->error(__('No rows were updated'));
        }
       
        // 启动事务
        Db::startTrans();
        try {
            $success = 0;
            $i=1;
            $level = Db::name('user_level')->column('id');
            foreach ($values as $key => $value) {
                if(!in_array($value[1], $level)){
                    throw new Exception('第'.$i.'行导入失败,用户等级不合法');
                }
                $find_user_id = Db::name('user')->where('mobile',$value[0])->value('id');
                if(!$find_user_id){
                    throw new Exception('第'.$i.'行导入失败,'.$value[0].'未注册');
                }else{
                    Db::name('user')->where('mobile',$value[0])->update(['level'=>$value[1]]);
                }
                
                $i++;
                $success++;
            }
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            Db::rollback(); 
            $this->error($msg);
        } catch (\Exception $e) {
            Db::rollback(); 
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('成功操作'.$success.'条数据');
    }

    public function kt($ids=null){
        $users  = Db::name('user')
        ->where('id','in',$ids)
        ->select();
                    
        if (!$users) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            // print_r($params);
            // die;
            if ($params) {
                $params = $this->preExcludeFields($params);
                $wallet_type = $params['params'];
                $amount = $params['amount'];
                //明细类型:资产类型:1=充值MU,2=活动MU,3=MQ
                $log_type = ['pay_mu'=>1,'active_mu'=>2,'mq'=>3];
                if($amount<0){
                    $this->error('投放数量无效');
                }
                Db::startTrans();
                try {
                    foreach ($users as $key => $value) {
                        $findUser =Db::name('user')
                        ->where(['id'=>$value['id']])
                        ->find();
                        Db::name('user')
                        ->where(['id'=>$value['id']])
                        ->update([
                        $wallet_type => Db::raw($wallet_type.'+'.$amount),
                        ]);
                        $balance_log['user_id']    = $value['id'];
                        $balance_log['amount']     = $amount;
                        $balance_log['before']     = $findUser[$wallet_type];
                        $balance_log['after']      = $findUser[$wallet_type]+$amount;
                        $balance_log['remark']     = '空投资产';
                        $balance_log['type']       = 1;
                        $balance_log['log_type']   = $log_type[$wallet_type];
                        $balance_log['source']     = 10;
                        $balance_log['createtime'] = time();
                        Db::name('user_balance_log')->insert($balance_log);
                    }
                    Db::commit();
                    $this->success();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
}
